#!/usr/bin/python
# -*- coding: UTF-8 -*-

import get_ip_position_python_online
import requests
import json

import pypinyin

city_list_file_name = "city_list.txt"

class CNWeather(object):
	"""docstring for CNWeather"""
	def __init__(self):
		self.cityname = ''
		self.citycode = ''
		self.temp = ''
		self.wind = ''
		self.humidity = ''
		self.weatheren = ''
		self.weathercode = ''
		self.pressure = ''
		self.json_data = ''

	def update_simple_weather(self, area_id):

		self.temp = ''
		self.wind = ''
		self.humidity = ''
		self.weatheren = ''
		self.weathercode = ''
		self.pressure = ''
		self.json_data = ''

		if area_id == '' or area_id == 0:
			return False

		sample_url = "http://d1.weather.com.cn/sk_2d/101020600.html?_=1608259116225"
		url = f"http://d1.weather.com.cn/sk_2d/{area_id}.html"
		headers = {
			# "Accept": "*/*",
			# "Accept-Encoding": "gzip, deflate",
			# "Accept-Language": "zh-CN,zh-TW;q=0.9,zh;q=0.8,en;q=0.7",
			# "Connection": "keep-alive",
			"Host": "d1.weather.com.cn",
			"Referer": f"http://www.weather.com.cn/weather1d/{area_id}.shtml",
			"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 YaBrowser/20.9.3.189 (beta) Yowser/2.5 Safari/537.36"
		}

		try:
			r = requests.get(url, headers=headers)
			r.encoding = 'utf-8'

			js_data = r.text
			# print(js_data)

			dataSK_index = js_data.find("var dataSK")
			if dataSK_index != -1:
				dataSK_var_start = js_data.find('{', dataSK_index)
				dataSK_var_end = js_data.find('}', dataSK_index)
				dataSK_var_data = js_data[dataSK_var_start: dataSK_var_end + 1]

				try:
					r_json = json.loads(dataSK_var_data)
					for d in r_json:
						if d == 'nameen':
							self.cityname = r_json[d]
						elif d == 'city':
							self.citycode = r_json[d]
						elif d == 'temp':
							self.temp = r_json[d]
						elif d == 'WD':
							self.wind = r_json[d]
						elif d == 'SD':
							self.humidity = r_json[d]
						elif d == 'weathere':
							self.weatheren = r_json[d]
						elif d == 'weathercode':
							self.weathercode = r_json[d]
						elif d == 'qy':
							self.pressure = r_json[d]

					self.json_data = json.dumps({"nameen": self.cityname, "citycode": self.citycode, "temp": self.temp, "humidity": self.humidity, "weatheren": self.weatheren, "weathercode": self.weathercode, "pressure": self.pressure})

					return True


				except Exception as e:
					print("ex:%s, json:\"%s\"" %(e, dataSK_var_data))
					return False

			else:
				print("Find dataSK failed, pls check r.text:\"%s\"" %(js_data))
				return False

		except Exception as e:
			print("ex:%s, province_code:\"%s" %(e, area_id))
			return False

	def __get_pinyin_from_zh(self, zh):
		py_list = []
		for n in pypinyin.pinyin(zh, style=pypinyin.NORMAL):
			py_list.append(n[0])
		return "".join(py_list)

	def get_city_id_by_city_name(self, name):
		self.name = name
		self.citycode = ''
		with open(city_list_file_name, "r") as f:
			f_json = json.loads(f.read())

		name_py = self.__get_pinyin_from_zh(name)

		for fj in f_json:
			for ffj in f_json[fj]:
				for fffj in f_json[fj][ffj]:
					fffj_py = self.__get_pinyin_from_zh(fffj)
					if fffj_py == name_py:
						self.citycode = f_json[fj][ffj][fffj]["AREAID"]
						return self.citycode

		return self.citycode


		
if __name__ == '__main__':

	w = CNWeather()
	w.get_city_id_by_city_name("哈尔滨")
	if w.update_simple_weather(w.citycode):
		print(w.temp)
		print(w.weathercode)
		print(w.json_data)
